package com.example.cinemasystemv2.controller;

import com.example.cinemasystemv2.entity.*;
import com.example.cinemasystemv2.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import jakarta.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Controller
@RequestMapping("/user")
public class UserController {
    
    @Autowired
    private MovieService movieService;
    
    @Autowired
    private ScreeningService screeningService;
    
    @Autowired
    private OrderService orderService;
    
    @Autowired
    private SnackService snackService;
    
    
    // 检查用户登录状态
    private boolean checkUserLogin(HttpSession session) {
        return session.getAttribute("username") != null;
    }
    
    // 用户仪表板
    @GetMapping("/dashboard")
    public String dashboard(Model model, HttpSession session) {
        if (!checkUserLogin(session)) {
            return "redirect:/login";
        }
        
        String username = (String) session.getAttribute("username");
        
        // 添加用户统计数据
        List<Order> userOrders = orderService.getOrdersByUsername(username);
        model.addAttribute("orderCount", userOrders.size());
        model.addAttribute("totalSpent", userOrders.stream().mapToDouble(Order::getAmount).sum());
        model.addAttribute("movieCount", movieService.getAllMovies().size());
        model.addAttribute("upcomingScreenings", screeningService.getUpcomingScreenings().size());
        
        // 添加最近订单
        model.addAttribute("recentOrders", userOrders.stream()
            .sorted((o1, o2) -> o2.getOrderTime().compareTo(o1.getOrderTime()))
            .limit(5)
            .toList());
        
        // 添加热门电影
        model.addAttribute("popularMovies", movieService.getAllMovies().stream().limit(6).toList());
        
        model.addAttribute("username", username);
        return "user/dashboard";
    }
    
    // 电影浏览
    @GetMapping("/movies")
    public String browseMovies(Model model, HttpSession session) {
        if (!checkUserLogin(session)) {
            return "redirect:/login";
        }
        
        model.addAttribute("movies", movieService.getAllMovies());
        return "user/movies";
    }
    
    @GetMapping("/movies/search")
    public String searchMovies(@RequestParam String keyword, Model model, HttpSession session) {
        if (!checkUserLogin(session)) {
            return "redirect:/login";
        }
        
        model.addAttribute("movies", movieService.searchMovies(keyword));
        model.addAttribute("keyword", keyword);
        return "user/movies";
    }
    
    // 场次浏览
    @GetMapping("/screenings")
    public String browseScreenings(Model model, HttpSession session) {
        if (!checkUserLogin(session)) {
            return "redirect:/login";
        }
        
        model.addAttribute("screenings", screeningService.getUpcomingScreenings());
        model.addAttribute("todayScreenings", screeningService.getTodayScreenings());
        return "user/screenings";
    }
    
    @GetMapping("/screenings/movie/{movieId}")
    public String screeningsByMovie(@PathVariable Long movieId, Model model, HttpSession session) {
        if (!checkUserLogin(session)) {
            return "redirect:/login";
        }
        
        Optional<Movie> movieOpt = movieService.getMovieById(movieId);
        if (movieOpt.isPresent()) {
            Movie movie = movieOpt.get();
            model.addAttribute("movie", movie);
            model.addAttribute("screenings", screeningService.getScreeningsByMovie(movie));
        }
        
        return "user/movie-screenings";
    }
    
    @GetMapping("/movie-screenings/{movieId}")
    public String movieScreeningsWithDate(@PathVariable Long movieId, 
                                         @RequestParam(required = false) String date,
                                         Model model, HttpSession session) {
        if (!checkUserLogin(session)) {
            return "redirect:/login";
        }
        
        Optional<Movie> movieOpt = movieService.getMovieById(movieId);
        if (movieOpt.isPresent()) {
            Movie movie = movieOpt.get();
            model.addAttribute("movie", movie);
            
            if (date != null && !date.isEmpty()) {
                try {
                    // 将字符串日期转换为LocalDateTime
                    LocalDateTime dateTime = LocalDateTime.parse(date + "T00:00:00");
                    model.addAttribute("selectedDate", date);
                    model.addAttribute("screenings", screeningService.getScreeningsByMovieAndDate(movie, dateTime));
                } catch (Exception e) {
                    // 如果日期格式错误，显示所有场次
                    model.addAttribute("screenings", screeningService.getScreeningsByMovie(movie));
                }
            } else {
                model.addAttribute("screenings", screeningService.getScreeningsByMovie(movie));
            }
        }
        
        return "user/movie-screenings";
    }
    
    // 座位选择和订票
    @GetMapping("/booking")
    public String bookingPage(@RequestParam Long screeningId, Model model, HttpSession session) {
        if (!checkUserLogin(session)) {
            return "redirect:/login";
        }
        
        Optional<Screening> screeningOpt = screeningService.getScreeningById(screeningId);
        if (screeningOpt.isPresent()) {
            Screening screening = screeningOpt.get();
            model.addAttribute("screening", screening);
            
            // 获取座位占用情况
            boolean[][] seatOccupancy = orderService.getSeatOccupancy(screening);
            model.addAttribute("seatOccupancy", seatOccupancy);
            
            return "user/booking";
        }
        
        return "redirect:/user/screenings";
    }
    
    @GetMapping("/book/{screeningId}")
    public String bookTicket(@PathVariable Long screeningId, Model model, HttpSession session) {
        if (!checkUserLogin(session)) {
            return "redirect:/login";
        }
        
        Optional<Screening> screeningOpt = screeningService.getScreeningById(screeningId);
        if (screeningOpt.isPresent()) {
            Screening screening = screeningOpt.get();
            model.addAttribute("screening", screening);
            
            // 获取座位占用情况
            boolean[][] seatOccupancy = orderService.getSeatOccupancy(screening);
            model.addAttribute("seatOccupancy", seatOccupancy);
            
            return "user/book-ticket";
        }
        
        return "redirect:/user/screenings";
    }
    
    @PostMapping("/book")
    public String confirmBooking(@RequestParam Long screeningId,
                                @RequestParam int row,
                                @RequestParam int seat,
                                HttpSession session,
                                RedirectAttributes redirectAttributes) {
        if (!checkUserLogin(session)) {
            return "redirect:/login";
        }
        
        try {
            String username = (String) session.getAttribute("username");
            Optional<Screening> screeningOpt = screeningService.getScreeningById(screeningId);
            
            if (screeningOpt.isPresent()) {
                Screening screening = screeningOpt.get();
                double amount = screening.getPrice();
                
                Order order = orderService.createOrder(username, screening, row, seat, amount);
                redirectAttributes.addFlashAttribute("success", "订票成功！订单号: " + order.getOrderId());
                
                return "redirect:/user/orders";
            } else {
                redirectAttributes.addFlashAttribute("error", "场次不存在");
            }
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "订票失败: " + e.getMessage());
        }
        
        return "redirect:/user/screenings";
    }
    
    // 我的订单
    @GetMapping("/orders")
    public String myOrders(Model model, HttpSession session) {
        if (!checkUserLogin(session)) {
            return "redirect:/login";
        }
        
        String username = (String) session.getAttribute("username");
        List<Order> orders = orderService.getOrdersByUsername(username);
        model.addAttribute("orders", orders);
        
        return "user/orders";
    }
    
    @PostMapping("/orders/refund/{orderId}")
    public String refundOrder(@PathVariable String orderId,
                             HttpSession session,
                             RedirectAttributes redirectAttributes) {
        if (!checkUserLogin(session)) {
            return "redirect:/login";
        }
        
        try {
            String username = (String) session.getAttribute("username");
            
            // 验证订单属于当前用户
            Optional<Order> orderOpt = orderService.getOrderByOrderId(orderId);
            if (orderOpt.isPresent() && orderOpt.get().getUsername().equals(username)) {
                Order refundedOrder = orderService.refundOrder(orderId);
                redirectAttributes.addFlashAttribute("success", 
                    "退票成功！退款金额: " + refundedOrder.getRefundAmount());
            } else {
                redirectAttributes.addFlashAttribute("error", "订单不存在或无权限");
            }
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "退票失败: " + e.getMessage());
        }
        
        return "redirect:/user/orders";
    }
    
    // 订单详情
    @GetMapping("/order-detail/{orderId}")
    public String orderDetail(@PathVariable String orderId, Model model, HttpSession session) {
        if (!checkUserLogin(session)) {
            return "redirect:/login";
        }
        
        String username = (String) session.getAttribute("username");
        
        try {
            Optional<Order> orderOpt = orderService.getOrderByOrderId(orderId);
            if (orderOpt.isEmpty() || !orderOpt.get().getUsername().equals(username)) {
                return "redirect:/user/orders";
            }
            
            model.addAttribute("order", orderOpt.get());
            return "user/order-detail";
        } catch (Exception e) {
            return "redirect:/user/orders";
        }
    }
    
    // 零食购买
    @GetMapping("/snacks")
    public String browseSnacks(Model model, HttpSession session) {
        if (!checkUserLogin(session)) {
            return "redirect:/login";
        }
        
        model.addAttribute("snacks", snackService.getAvailableSnacks());
        return "user/snacks";
    }
    
    @PostMapping("/snacks/buy")
    public String buySnack(@RequestParam Long snackId,
                          @RequestParam int quantity,
                          HttpSession session,
                          RedirectAttributes redirectAttributes) {
        if (!checkUserLogin(session)) {
            return "redirect:/login";
        }
        
        try {
            String username = (String) session.getAttribute("username");
            boolean success = snackService.sellSnack(snackId, quantity, username);
            
            if (success) {
                Optional<Snack> snackOpt = snackService.getSnackById(snackId);
                if (snackOpt.isPresent()) {
                    double totalAmount = snackOpt.get().getPrice() * quantity;
                    redirectAttributes.addFlashAttribute("success", 
                        "购买成功！总金额: " + totalAmount + "元");
                }
            }
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "购买失败: " + e.getMessage());
        }
        
        return "redirect:/user/snacks";
    }
    
    // 个人中心
    @GetMapping("/profile")
    public String userProfile(Model model, HttpSession session) {
        if (!checkUserLogin(session)) {
            return "redirect:/login";
        }
        
        String username = (String) session.getAttribute("username");
        
        // 获取用户统计信息
        List<Order> userOrders = orderService.getOrdersByUsername(username);
        long totalOrders = userOrders.size();
        long activeOrders = userOrders.stream().filter(order -> !order.isRefunded()).count();
        double totalSpent = userOrders.stream()
            .filter(order -> !order.isRefunded())
            .mapToDouble(Order::getAmount)
            .sum();
        
        model.addAttribute("totalOrders", totalOrders);
        model.addAttribute("activeOrders", activeOrders);
        model.addAttribute("totalSpent", totalSpent);
        model.addAttribute("recentOrders", userOrders.stream().limit(5).toArray());
        
        return "user/profile";
    }
}